package com.example.play


import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.common.entity.SimpleVideoEntity
import com.blankj.utilcode.util.LogUtils
import com.example.base.RouterPath
import com.example.common.mvi.BaseMviActivity
import com.example.common.view.SnapPageLayoutManager
import com.example.play.adapter.PlayVideoAdapter
import com.example.play.databinding.ActivityPlayBinding
import com.example.play.intent.PlayViewIntent
import com.example.play.state.PlayUiState
import com.example.play.vm.PlayViewModel
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = RouterPath.PATH_PLAY_PAGE)
@AndroidEntryPoint
class PlayActivity : BaseMviActivity<ActivityPlayBinding>() {

    @Autowired
    lateinit var videoEntity:SimpleVideoEntity

    @Autowired
    @JvmField
    var typeId:Int = -1

    @Autowired
    @JvmField
    var channelId:String = ""

    private var mCurrentPageIndex:Int = 0
    private var pageIndex = 1
    private var pageSize = 10
    private val mViewModel :PlayViewModel by viewModels()
    private var mVideoPlayer : StandardGSYVideoPlayer? = null
    //视频集合
    private var videoList = mutableListOf<SimpleVideoEntity>()
    //适配器
    private lateinit var mVideoAdapter:PlayVideoAdapter
    //
    private lateinit var snapPageLayoutManager: SnapPageLayoutManager


    override fun initViews() {
        //自动注入参数
        ARouter.getInstance().inject(this)
        //传递进来的数据当成第一条数据添加
        videoEntity.let {
            videoList.add(it)
        }




        //下拉刷新和加载更多事件监听
        mDatabinding.smart.setOnRefreshLoadMoreListener(object:OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {

            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {

            }
        })

        snapPageLayoutManager = SnapPageLayoutManager(this@PlayActivity)
        mDatabinding.rvVideo.layoutManager = snapPageLayoutManager
        mVideoAdapter = PlayVideoAdapter(videoList)



        //添加列表滚动事件
        mDatabinding.rvVideo.addOnScrollListener(object:RecyclerView.OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                mCurrentPageIndex = snapPageLayoutManager.findFirstVisibleItemPosition()
                videoEntity = videoList[mCurrentPageIndex]
                //获取当前Item布局中的GSY播放器
                mVideoPlayer = (mDatabinding.rvVideo.findViewHolderForLayoutPosition(mCurrentPageIndex)as PlayVideoAdapter.VideoPlayViewHodel).dataBinding.gsyPlayer
                //播放视频
                mVideoPlayer?.isLooping = true//开启循环播放
                mVideoPlayer?.startPlayLogic()
            }
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if(newState == RecyclerView.SCROLL_STATE_DRAGGING){
                    mVideoPlayer?.release()
                }
            }
        })


        //局部更新UI
        mDatabinding.rvVideo.swapAdapter(mVideoAdapter, true)
    }

    override fun getLayoutId(): Int =R.layout.activity_play

    private fun loadMoreOrRefresh(){

    }

    override suspend fun sendViewIntent() {
        lifecycleScope.launch {
            if(typeId == -1){
                mViewModel.channel.send(PlayViewIntent.LoadRecommendSimpleVideoList(pageIndex,pageSize))
            }else{
                mViewModel.channel.send(PlayViewIntent.LoadSimpleVideoListById(channelId,pageIndex,pageSize))
            }
        }
    }

    override suspend fun collectUiState() {

        mViewModel.uiState.collect{

            when(it){
                is PlayUiState.LoadSimpleVideoSuccess->{
                    videoList.clear()
                    videoList.addAll(it.list)
                    mVideoAdapter.notifyDataSetChanged()

                }
                is PlayUiState.LoadSimpleVideoFail->{
                    showToast(it.msg)
                }
            }
        }
    }
    override fun onResume() {
        mVideoPlayer?.onVideoResume()
        super.onResume()
    }

    override fun onPause() {
        mVideoPlayer?.onVideoPause()
        super.onPause()
    }

    override fun onDestroy() {
        mVideoPlayer?.release()
        mVideoPlayer = null //方便GC回收
        super.onDestroy()
    }

}